package com.hefan.api.service.monitor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ImCustomMsgEnum;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LiveLog;
import com.hefan.live.bean.LiveRoomVo;
import com.hefan.live.bean.WarnLog;
import com.hefan.monitor.itf.MonitorService;
import com.hefan.oms.bean.ImCustomMsgVo;
import com.hefan.user.bean.ThirdPartyUser;
import com.hefan.user.bean.WebUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lxw on 2016/10/29.
 */
@Component
public class LiveMonitorLocalService {

	private Logger logger = LoggerFactory.getLogger(LiveMonitorLocalService.class);



	@Reference
	MonitorService monitorService;

	/**
	 * 直播断流处理
	 * @param userId
	 * @param chartRoomId
	 * @param liveUuid
     * @return
     */
	public ResultBean closeLivingOpreate(String userId, String chartRoomId, String liveUuid,String promptCopy) {
		return monitorService.closeLiving(userId,chartRoomId,liveUuid,promptCopy);
	}

	public int warningLiving(WarnLog warnLog,String anchorWaringMsg){
		warnLog.setWarnContent(anchorWaringMsg);
		int us = this.monitorService.saveWarnLog(warnLog);
		if (us > 0) {
			// 发警告广播
			ImCustomMsgVo m = new ImCustomMsgVo();
			m.setType(ImCustomMsgEnum.AnchorWaringMsg.getType());
			m.setContent(anchorWaringMsg);
			WebUser webUser = monitorService.getWebUserInfoByUserId(warnLog.getUserId());
			ThirdPartyUser user = new ThirdPartyUser();
            user.setHeadImg(webUser.getHeadImg());
            user.setUserLevel(webUser.getUserLevel());
            user.setNickName(webUser.getNickName());
            user.setUserId(webUser.getUserId());
            user.setUserType(webUser.getUserType());
            user.setLiveUuid(warnLog.getLiveUuid());
			monitorService.chatroomSendMsg(warnLog.getChatRoomId(), GlobalConstants.HEFAN_OFFICIAL_ID, 100, 0,
					JSON.toJSON(m).toString(), JSON.toJSON(user).toString());
		}
		return us;
	}

	public int LiveRoomHighStatus(String userId,String liveUuid,int risk,String optUserId) {
		return this.monitorService.updateLiveHighStatus(userId,liveUuid,risk,optUserId);
	}

	public List getPunishTypeList() {
		List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
		List getList = this.monitorService.getPunishTypeList();
		Map<String, List<Map>> resultMap = new HashMap<String, List<Map>>(); // 按照违规类型分组
		if (CollectionUtils.isNotEmpty(getList)) {
			for (int i = 0; i < getList.size(); i++) {
				Map dataItem = (Map) getList.get(i);
				if (resultMap.containsKey(MapUtils.getStrValue(dataItem, "category", ""))) {
					// 加入分组
					resultMap.get(MapUtils.getStrValue(dataItem, "category", "")).add(dataItem);
				} else {
					// 创建新的分组
					List<Map> nlist = new ArrayList<Map>();
					nlist.add(dataItem);
					resultMap.put(MapUtils.getStrValue(dataItem, "category", ""), nlist);
				}
			}
		}
		if (resultMap != null && !resultMap.isEmpty()) {
			if (resultMap.get("1") != null && resultMap.get("1").size() > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("category", 1);
				map.put("categoryName", "涉黄");
				map.put("punishType", resultMap.get("1"));
				resList.add(map);
			}
			if (resultMap.get("2") != null && resultMap.get("2").size() > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("category", 2);
				map.put("categoryName", "涉政宗教");
				map.put("punishType", resultMap.get("2"));
				resList.add(map);
			}
			if (resultMap.get("3") != null && resultMap.get("3").size() > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("category", 3);
				map.put("categoryName", "涉赌摄枪支");
				map.put("punishType", resultMap.get("3"));
				resList.add(map);
			}
			if (resultMap.get("4") != null && resultMap.get("4").size() > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("category", 4);
				map.put("categoryName", "宣传广告冒充官网");
				map.put("punishType", resultMap.get("4"));
				resList.add(map);
			}
			if (resultMap.get("5") != null && resultMap.get("5").size() > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("category", 5);
				map.put("categoryName", "私密直播");
				map.put("punishType", resultMap.get("5"));
				resList.add(map);
			}
			if (resultMap.get("6") != null && resultMap.get("6").size() > 0) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("category", 6);
				map.put("categoryName", "其他");
				map.put("punishType", resultMap.get("6"));
				resList.add(map);
			}
		}
		return resList;
	}

	public int dealPunishDetal(String userId, String optUserId, Map map, String punishReason, String illegalPic,String liveUuid,int punishTypeFromTb, int punishDataType) {
		
		return this.monitorService.dealPunishDetal(userId, optUserId, map, punishReason, illegalPic,liveUuid,punishTypeFromTb,punishDataType);
	}

	public Map getPunishTypeById(long typeId,int punishTypeFromTb) {
		return this.monitorService.getPunishTypeById(typeId,punishTypeFromTb);
	}

	public List getPunishList() {
		List resList = new ArrayList();
		List<Map<String,Object>> pushList = this.monitorService.getPunishDetail();
		String pre = DynamicProperties.getString("replay.domain.pre");
		String suf = DynamicProperties.getString("replay.domain.suf");
		for(int i=0;i<pushList.size();i++){
			Map<String,Object> resMap = new HashMap<String,Object>();
			Map<String,Object> map = pushList.get(i);
			resMap.put("userId", "");
			if(map.containsKey("user_id")){
				resMap.put("userId", map.get("user_id")==null?"":map.get("user_id").toString());
			}
			resMap.put("nickName", "");
			if(map.containsKey("nick_name")){
				resMap.put("nickName", map.get("nick_name")==null?"":map.get("nick_name").toString());
			}
			resMap.put("punishReason", "");
			if(map.containsKey("punish_reason") && map.get("punish_reason")!=null){
				resMap.put("punishReason", map.get("punish_reason")==null?"":map.get("punish_reason").toString());
			}
			resMap.put("categoryName", "");
			if(map.containsKey("category") && map.get("category") !=null){
				String category = map.get("category").toString();
				if(category.equals("1")){
					resMap.put("categoryName", "涉黄");
					resMap.put("punishReason","涉黄");
				}else if(category.equals("2")){
					resMap.put("categoryName", "摄政宗教");
					resMap.put("punishReason", "摄政宗教");
				}else if(category.equals("3")){
					resMap.put("categoryName", "摄赌摄枪支");
					resMap.put("punishReason", "摄赌摄枪支");
				}else if(category.equals("4")){
					resMap.put("categoryName", "宣传广告冒充官网");
					resMap.put("punishReason", "宣传广告冒充官网");
				}else if(category.equals("5")){
					resMap.put("categoryName", "私密直播");
					resMap.put("punishReason", "私密直播");
				}else{
					resMap.put("categoryName", "其他");
				}
			}
			resMap.put("typeName", "");
			if(map.containsKey("type_name") && map.get("type_name")!=null){
				resMap.put("typeName", map.get("type_name").toString());
			}
			resMap.put("illegalPic", "");
			resMap.put("illegalPicTime", "");
			if(map.containsKey("illegal_pic") && map.get("illegal_pic")!=null){
				if(StringUtils.isNotBlank("illegal_pic")){
					try {
						String illegal_pic = java.net.URLDecoder.decode(map.get("illegal_pic").toString(),   "utf-8");
						resMap.put("illegalPic", illegal_pic);
						String url = illegal_pic.substring(0, illegal_pic.lastIndexOf("/"));
						String liveUuid = url.substring(url.lastIndexOf("/")+1);
						String picUrl = illegal_pic.substring(0, illegal_pic.lastIndexOf("."));
						int picNum = Integer.parseInt(picUrl.substring(picUrl.lastIndexOf("/")+1));
						LiveLog liveLog = monitorService.getLiveLogByUuid(liveUuid);
						if(liveLog !=null && picNum > 0){
							SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							resMap.put("illegalPicTime", df.format(liveLog.getStartTime()==null?"":(liveLog.getStartTime().getTime() + picNum*5*1000)));
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						logger.info("处罚列表图片解析图片时间失败"+e.getMessage());
					}
				}
			}
			resMap.put("fromTypeName", "");
			if(map.containsKey("from_type") && map.get("from_type") !=null){
				if(map.get("from_type").toString().equals("0")){
					resMap.put("fromTypeName", "后台");
				}else{
					resMap.put("fromTypeName", "监控");
				}
			}
			resMap.put("freezeDays", "");
			if(map.containsKey("freeze_days")){
				resMap.put("freezeDays", map.get("freeze_days")==null?"":map.get("freeze_days").toString());
			}
			resMap.put("stopDays", "");
			if(map.containsKey("stop_days")){
				resMap.put("stopDays", map.get("stop_days")==null?"":map.get("stop_days").toString());
			}
			resMap.put("dedMoney", "");
			if(map.containsKey("ded_money")){
				resMap.put("dedMoney", map.get("ded_money")==null?"":map.get("ded_money").toString());
			}
			resMap.put("dedCommision", "");
			if(map.containsKey("ded_commision")){
				resMap.put("dedCommision", map.get("ded_commision")==null?"":map.get("ded_commision").toString());
			}
			resMap.put("cancelFlag", "");
			if(map.containsKey("cancel_flag")){
				resMap.put("cancelFlag", map.get("cancel_flag")==null?"":map.get("cancel_flag").toString());
			}
			resMap.put("cancelUser", "");
			if(map.containsKey("cancel_user")){
				resMap.put("cancelUser", map.get("cancel_user")==null?"":map.get("cancel_user").toString());
			}
			resMap.put("cancelReason", "");
			if(map.containsKey("cancel_reason")){
				resMap.put("cancelReason", map.get("cancel_reason")==null?"":map.get("cancel_reason").toString());
			}
			resMap.put("cancelTime", "");
			if(map.containsKey("cancelTime")){
				resMap.put("cancelTime", map.get("cancelTime")==null?"":map.get("canceTime").toString());
			}
			resMap.put("createTime", "");
			if(map.containsKey("createTime")){
				resMap.put("createTime", map.get("createTime")==null?"":map.get("createTime").toString());
			}
			resMap.put("createUser", "admin");
			if(map.containsKey("create_user") && map.get("create_user")!=null){
				resMap.put("createUser", StringUtils.isBlank(map.get("create_user").toString())?"admin":map.get("create_user").toString());
			}
			resMap.put("playbackUrl","");
			if(map.containsKey("live_uuid") && map.get("live_uuid")!=null){
				String liveUuid = map.get("live_uuid").toString();
				if(StringUtils.isNotBlank(liveUuid)){
					resMap.put("playbackUrl",pre + liveUuid+ suf );
				}
			}
			resList.add(resMap);
		}
		return resList;
	}

	public List<LiveRoomVo> getLivingList(Page po) {
		return this.monitorService.getLivingList(po);
	}

	public LiveRoomVo findLiveRoomByIdFormonitor(String userId, String uuid) {
		return monitorService.findLiveRoomByIdFormonitor(userId, uuid);
	}
	
	public List getHighRiskLiveList(String userId,String nickName,String startTime,String endTime){
		List resList = new ArrayList();
		List list = this.monitorService.getHighRiskLiveList(userId, nickName, startTime, endTime);
		if(!CollectionUtils.isEmptyList(list)){
			String pre = DynamicProperties.getString("replay.domain.pre");
			String suf = DynamicProperties.getString("replay.domain.suf");
			for(int i=0;i<list.size();i++){
				Map<String,Object> resMap = new HashMap<String,Object>();
				Map map = (Map)list.get(i);
				resMap.put("userId","");
				if(map.containsKey("user_id") && map.get("user_id")!=null){
					resMap.put("userId", StringUtils.isBlank(map.get("user_id").toString())?"":map.get("user_id").toString());
				}
				resMap.put("userType", -1);
				if(map.containsKey("user_type") && map.get("user_type")!=null){
					resMap.put("userType", StringUtils.isBlank(map.get("user_type").toString())?-1:Integer.parseInt(map.get("user_type").toString()));
				}
				resMap.put("nickName","");
				if(map.containsKey("nick_name") && map.get("nick_name")!=null){
					resMap.put("nickName", StringUtils.isBlank(map.get("nick_name").toString())?"":map.get("nick_name").toString());
				}
				resMap.put("playbackUrl","");
				if(map.containsKey("live_uuid") && map.get("live_uuid")!=null){
					String liveUuid = map.get("live_uuid").toString();
					if(StringUtils.isNotBlank(liveUuid)){
						resMap.put("playbackUrl",pre + liveUuid+ suf );
					}
				}
				resMap.put("playbackTime","");
				if(map.containsKey("back_time") && map.get("back_time")!=null){
					resMap.put("playbackTime", StringUtils.isBlank(map.get("back_time").toString())?"":map.get("back_time").toString());
				}
				resMap.put("poster","");
				if(map.containsKey("live_img") && map.get("live_img")!=null){
					resMap.put("poster", StringUtils.isBlank(map.get("live_img").toString())?"":map.get("live_img").toString());
				}
				resList.add(resMap);
			}
		}
		return resList;
	}
	
	public ResultBean updateLiveInfoForMonitor(String liveName, String liveImg, String liveUuid, String anthId) {
		// TODO Auto-generated method stub
		return monitorService.updateLiveInfoForMonitor(liveName, liveImg, liveUuid, anthId);
	}
}
